"""
通用函数集
"""
import requests
# import json
from os import path, mkdir
from requests.exceptions import *
from urllib3.exceptions import *

__all__ = ['getHtml', 'chdir_']

chdir_ = r'D:\phpstudy_pro\WWW\1024.local\support'


def _writer(dir, file_name, file):
    """
    mkdir
    :param dir:
    :param file:
    :return:
    """
    _dir = ''
    for i in dir.split('/'):
        _dir = _dir + i + '/'
        if not path.exists(_dir): mkdir(_dir)
    with open(f"{dir}/{file_name}", mode='w', encoding='utf8')as f:
        f.write(f"{file}")
    return 'ok'


def getHtml(url, headers=None):
    """ get a code from a html through url.
    获取任意一个网页的源代码，以字符串的形式返回。
    :param url: 请求url；
    :param headers: 请求头；
    :type headers: dict
    :return url的响应结果。（响应头， 响应体）
    """
    # global page
    headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
    try:
        page = requests.get(url, headers=headers)
        page.encoding = "utf-8"
        if page.status_code is 200:
            _head = page.headers
            # _head = json.loads(_headers)
            page = page.text

        else:
            print("网页获取获取错误。")
            return 'Error'
    except ConnectionError:
        print("连接错误")
        return 'Error'
    except TimeoutError:
        print("连接超时")
        return 'Error'
    _writer('./Support', 'Temp.html', page)
    return _head, page


if __name__ == '__main__':
    f_tmp = 'tmp_3_html.html'
    ht_ = 'http://q1.c603ba473f8.xyz/pw/html_data/3/1911/4440224.html'
    a = getHtml(ht_)
    html_info = a[1].replace('&&nbsp;', ' ')
    html_info = html_info.replace('<br>', '\n')

    open(f_tmp, 'w', encoding='utf8').write(a[1])
    print(a[0])
